<template>
    <div class="app-container">
        <el-row :gutter="100">
            <el-col :span="6">
                <el-form ref="form" :model="form" :rules="rules" label-width="150px">
                    <el-form-item label="赠送时间："  prop="end_signed">
                        <el-date-picker v-model="form.end_signed" style="width: 240px" value-format="yyyy-MM-dd" type="date" placeholder="请选择赠送日期"></el-date-picker>
                    </el-form-item>
                    <el-form-item label="赠送区片：" prop="community_id">
                        <el-select v-model="form.community_id" placeholder="请选择区片" size="small" class="w120 mr-10"  @change="changeCommunityMachine" >
                            <el-option v-for="(item, index) in communityList" :key="index" :label="item.title" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="客户：" prop="user_id">
                        <el-select v-model="form.user_id"
                                   filterable
                                   placeholder="请选择客户" size="small"  @change="changeUserWaterMachine">
                            <el-option v-for="(item, index) in userSelectList" :key="index"   :label="item.nickname+'('+item.mobile+')'" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="总积分：">
                        <el-input type="number"  v-model="form.score" placeholder="请输入总积分"></el-input>
                    </el-form-item>
                    <el-form-item label="积分分成比例：" prop="proportion">
                        <el-input type="text"  min="1" v-model="form.proportion" @input="calculateRatioProportion" placeholder="请输入积分比例"></el-input>
                    </el-form-item>

                    <el-form-item label="上级：" prop="spread_uid">
                        <el-select v-model="form.spread_uid"
                                   filterable
                                   placeholder="请选择上级客户" size="small"  @change="changeUserWaterMachine">
                            <el-option v-for="(item, index) in userSelectList" :key="index"   :label="item.nickname+'('+item.mobile+')'" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="上级应得积分比例：" prop="manage_ratio">
                        <el-input type="text"  min="1" v-model="form.manage_ratio" @input="calculateRatioProportion" placeholder="请输入积分分成比例"></el-input>
                    </el-form-item>
                    <el-form-item label="上级积分分成：">
                        <el-input type="number"  v-model="form.manage_score" placeholder="请输入积分数量"></el-input>
                    </el-form-item>
                </el-form>
                <el-form label-width="100px" style="margin-top:50px;">
                    <el-form-item style="margin-left:-50px;margin-top:10px;">
                        <el-button size="small" type="primary" @click="submitForm">保 存</el-button>
                    </el-form-item>
                </el-form>
            </el-col>
            <el-col :span="16">
                <el-form :model="formjunda" ref="formjunda" :roles="formjundaRules"  :inline="true">
                    <el-form-item label="时间骏达用户uuid：" prop="junda_uuid">
                        <el-input type="text"  v-model="formjunda.junda_uuid" placeholder="请输入骏达uuid"></el-input>
                        <el-tag type="danger">时间：{{formjunda_signed}}</el-tag><el-tag type="danger">骏达后台：http://oa.ljda.net/#/businfo/ConsumeDetail，获取方式（F12，点击最后一个url , 在 Request Headers中最后一个参数）</el-tag>
                    </el-form-item>
                </el-form>
                <el-table  ref="historyWater" width="99vw"  size="small"
                           :data="waterMachineData">
                    <el-table-column show-overflow-tooltip prop="water_title" label="水机名称" align="center" width="180px"/>
                    <el-table-column align="center" label="所属片区" width="80px">
                        <template slot-scope="{row}">
                            {{ row.community? row.community.title : "" }}
                        </template>
                    </el-table-column>
                    <el-table-column align="center" label="身份" width="80px">
                        <template slot-scope="{row}">
                            <dict-tag :options="dict.type.sys_user_water_role" :value="row.water_role" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="sum_score" label="总积分" show-overflow-tooltip width="160px">
                        <template slot-scope="{row}">
                            <div class="input-box">
                                <el-input size="small" v-model="row.sum_score" style="width:50%;" @input="calculateRow(row)"   ></el-input>
                                <el-button type="primary" size="mini" @click="handleEditScoreCount(row)">获取</el-button>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="proportion" label="积分分成比例(整数)" show-overflow-tooltip width="150px">
                        <template slot-scope="{row}">
                            <div class="input-box">
                                <el-input size="small" v-model="row.proportion" style="width:100%;"  @input="calculateRow(row)" ></el-input>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="score" label="积分分成" show-overflow-tooltip width="120px">
                        <template slot-scope="{row}">
                            <div class="input-box">
                                <el-input size="small" v-model="row.score" style="width:100%;" ></el-input>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="proportion" label="上级积分分成比例(整数)" show-overflow-tooltip width="180px">
                        <template slot-scope="{row}">
                            <div class="input-box">
                                <el-input size="small" v-model="row.manage_ratio " style="width:100%;"  @input="calculateRow(row)" ></el-input>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="score" label="上级积分分成" show-overflow-tooltip width="150px">
                        <template slot-scope="{row}">
                            <div class="input-box">
                                <el-input size="small" v-model="row.manage_score" style="width:100%;" ></el-input>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </el-col>
        </el-row>
    </div>

</template>

<script>



import { getAllCom } from "@/api/grzq/community.js";
import { getApparatusAllList,getUserApparatusAllList } from "@/api/grzq/apparatus.js";
import {getUsersBuySelectlists} from "@/api/grzq/user_buy.js";
import {  createScore,createJundaScore} from "@/api/grzq/buy_scores.js";


export default {
    name: 'site-edit',
    dicts:['sys_user_water_role'],
    data() {
        return {
            dialogVisible:false,
            // 表单校验
            rules: {
                end_signed:[
                    {required: true, message: "请选择赠送时间", trigger: "blur"}
                ],
                community_id:[
                    {required: true, message: "请选择所属片区", trigger: "blur"}
                ],
                user_id:[
                    {required: true, message: "请选择所属客户", trigger: "blur"}
                ],
                proportion:[
                    {required: true, message: "请输入赠送比例", trigger: "blur"}
                ],
            },
            form:{},
            formjunda_signed:'',
            communityList: [],
            waterMachineData:[],
            userSelectList:[],
            formjundaRules: {
                junda_uuid: [
                    {required: true, message: "上级部门不能为空", trigger: "blur"}
                ]
            },
            formjunda:{
                junda_uuid:'7e479ba5-ef02-404b-9a34-b1f0012f8c09',
                equipment_name1:'',
                equipment_name2:'',
                score:0
            },
            junda_uuid:'',
            jundaWaterData:[]
        }
    },
    async created() {
        this.reset()
        await this.getAllCom()
        await this.UsersBuySelectlist()
    },
    methods: {
        reset() {
            this.form = {
                user_id: '',
                community_id: '',
                score: 0,
                end_signed: '',
                proportion: 0,
                score_proportion: 0,
                manage_ratio: 0,
                manage_score: 0,
                waterMachineData: [],
                userWithWeaterDeviceData: [],
            }
            this.resetForm('form')
        },
        resetTime() {
            this.form = {
                score: 0,
                proportion: 0,
            }
            this.resetForm('form')
        },
        // 片区
        async getAllCom() {
            const res = await getAllCom();
            this.communityList = res.data;
        },
        async getUserWaterDevice(userId) {
            console.log(userId)
            const {data} = await getUserApparatusAllList({userId: userId});
            return data
        },
        // 点击片区
        async changeCommunityMachine(id){
            let _self = this
            if (!_self.form.end_signed){
                _self.msgError("请选择赠送日期时间")
            }else {
                _self.form.score =0
                _self.form.score_proportion =0
                _self.form.manage_score =0

                let junda_uuid = this.formjunda.junda_uuid;
                let start_date = this.form.end_signed;
                const community_info = this.communityList.find((item) => item.id === id)
                _self.form.user_id = community_info.user_id
                let userId = community_info.user_id
                const {data} = await getUserApparatusAllList({userId: userId});
                const  userWithWeaterDeviceData = data;
                // 用户 id
                const user_info = this.userSelectList.find((item) => item.id === userId)
                _self.form.spread_uid = user_info.spread_uid
                _self.form.proportion = user_info.sharing_ratio;
                _self.form.manage_ratio = user_info.manage_ratio;
                console.log("user_info",user_info)
                _self.waterMachineData =userWithWeaterDeviceData

                 for(let item of userWithWeaterDeviceData){
                     console.log("item",item)
                     let water_id = item.water_id;
                     createJundaScore({
                         'junda_uuid': junda_uuid,
                         'start_date': start_date,
                         'water_id':water_id
                     }).then(res=>{
                         let jd_sum_score =  res.data.score;
                         item.sum_score = res.data.score;
                         item.proportion = user_info.sharing_ratio;
                         item.spread_uid = user_info.spread_uid;
                         console.log("_self.form.end_signed >= item.manage_profit_date",_self.form.end_signed >= item.manage_profit_date)

                         if (_self.form.end_signed >= item.manage_profit_date && item.manage_profit_date){
                             console.log('可以分')
                         }else {
                             console.log('不可以分')
                         }

                         if (user_info.spread_uid!=0){
                             //
                             // 本身
                             item.proportion = user_info.sharing_ratio;
                             //应得积分 =  总积分*（本身比例 - 上级比例）/100
                             item.score =  (jd_sum_score * ((user_info.sharing_ratio - user_info.manage_ratio) / 100)).toFixed(3) // 根据分数和比例计算值
                             _self.form.score =_self.form.score + jd_sum_score
                             _self.form.score_proportion = _self.totalScoreProportion(_self.form.score_proportion ,item.score)
                             item.score_proportion =  (jd_sum_score * (user_info.manage_ratio / 100)).toFixed(3) // shangji
                             // 上级
                             // if (_self.form.end_signed <= item.manage_profit_date)
                             item.manage_ratio = _self.form.manage_ratio
                             item.manage_score =  (jd_sum_score * (_self.form.manage_ratio / 100)).toFixed(3) // 上级应得积分
                             //上级应得积分 总
                             _self.form.manage_score +=Number(item.manage_score)

                             console.log(" 上级应得积分", _self.form.manage_score)
                         }else {
                             item.proportion = user_info.sharing_ratio;
                             item.score =  (jd_sum_score * (user_info.sharing_ratio / 100)).toFixed(3) // 根据分数和比例计算值
                             _self.form.score =_self.form.score + jd_sum_score
                             _self.form.score_proportion = _self.totalScoreProportion(_self.form.score_proportion ,item.score)
                         }
                     })
                 }
            }

        },

        handleEditScoreCount(row){
            console.log(row)
            this.start_date = this.form.end_signed;
            let start_date = this.form.end_signed;
            let junda_uuid = this.formjunda.junda_uuid;
            let water_id = row.water_id;
            createJundaScore({
                'junda_uuid': junda_uuid,
                'start_date': start_date,
                'water_id':water_id
            }).then(res=>{
                row.sum_score = res.data.score;
                row.proportion = this.form.proportion;
                this.calculateRow(row);
                this.msgSuccess('获取成功')
            })
        },

        /** 提交按钮 */
        submitForm: function() {
            let that = this;
            that.form.waterMachineData = that.waterMachineData
            console.log("that.form", that.form)
            this.$refs['form'].validate(async valid => {
                if (valid) {
                    const {data,msg, status} = await createScore(that.form)
                    if (!data){
                        that.msgError(msg)
                    }else {
                        this.resetTime()
                        that.msgSuccess('赠送成功')
                    }
                }
            })
        },
        //获取列表
        async UsersBuySelectlist() {
            const {data, status, msg} = await getUsersBuySelectlists({'water_role':'buy'});
            this.userSelectList = data;
        },

        async changeUserWaterMachine(userId) {
            console.log(userId)
            const {data} = await getUserApparatusAllList({userId: userId});
            this.waterMachineData = data;
            const user_info = this.userSelectList.find((item) => item.id === userId)
            console.log("user_info",user_info)
            this.form.proportion = user_info.sharing_ratio;
            this.form.manage_ratio = user_info.manage_ratio;

        },


        calculateRatioProportion() {
            const {score, proportion,manage_ratio} = this.form;
            // 计算每个项目的值
            this.waterMachineData = this.waterMachineData.map(item => ({
                ...item,
                proportion: proportion,// 根据分数和比例计算值
                score: (item.sum_score * (manage_ratio!=0?(proportion-manage_ratio)/100: proportion/ 100)).toFixed(3), // 根据分数和比例计算值
                manage_ratio:manage_ratio,
                manage_score:(item.sum_score * (manage_ratio / 100)).toFixed(3), // 根据分数和比例计算值
            }));
            this.form.score = this.totalScore()
            console.log(" this.form.score ", this.form.score)
        },

        calculateRow(row) {
            row.score = (row.sum_score * (row.proportion / 100)).toFixed(3);
            this.form.score = this.totalScore()
        },
        totalScore() {
            return this.waterMachineData.reduce((sum, row) => {
                return (parseFloat(sum) + parseFloat(row.sum_score)).toFixed(2);
            }, 0);
        },
        totalScoreProportion(sum,sum_score) {
            return (parseFloat(sum) + parseFloat(sum_score)).toFixed(2);
        },
    }
}
</script>

<style scoped>

</style>
